package org.xiaohanghu.starter.net;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.xiaohanghu.starter.StringUtils;


/**
 * @author xiaohanghu
 */
public class UrlFactory {

	private String defaultScheme;

	private String separator = ",";

	private Map<String, UrlConvertor> convertors = new HashMap<String, UrlConvertor>();

	public void setDefaultScheme(String defaultScheme) {
		this.defaultScheme = defaultScheme;
	}

	public void addUrlConvertor(String scheme, UrlConvertor urlConvertor) {
		this.convertors.put(scheme, urlConvertor);
	}

	public String getSeparator() {
		return separator;
	}

	public void setSeparator(String separator) {
		this.separator = separator;
	}

	public URL toUrl(URI uri) throws MalformedURLException, URISyntaxException {
		if (null == uri) {
			return null;
		}
		try {
			return uri.toURL();
		} catch (MalformedURLException e) {
			String scheme = uri.getScheme();
			if (null == scheme) {
				scheme = defaultScheme;
//				throw e;
			}
			UrlConvertor urlConvertor = convertors.get(scheme);
			if (null == urlConvertor) {
				String path = uri.toString();
				if (!path.startsWith("/")) {
					path = "/" + path;
				}
				path = defaultScheme + ":" + path;
				return new URL(path);
			}
			return urlConvertor.convert(uri);
		}
	}

	public URL toUrl(String str, URI currentUri) throws URISyntaxException,
			MalformedURLException {
		URI uri = UrlUtils.toUrl(str, currentUri);
		return toUrl(uri);
	}

	public List<URL> toUrls(String urisStr, URI currentUri)
			throws MalformedURLException, URISyntaxException {
		List<URL> result = new ArrayList<URL>();
		urisStr = StringUtils.trimToNull(urisStr);
		if (null == urisStr) {
			return result;
		}
		String[] strs = split(urisStr);
		for (String str : strs) {
			URL url = toUrl(str, currentUri);
			if (null != url) {
				result.add(url);
			}
		}
		return result;
	}

	protected String[] split(String config) {
		config = StringUtils.trimToNull(config);
		if (null == config) {
			return null;
		}
		String[] result = config.split(separator);
		return result;
	}

}
